#include <iostream>
#include <mysql/mysql.h>
#include <unistd.h>
#include <string>

const std::string host="localhost";
const std::string user="connector";
const std::string password="LCQ010723@lcq163.com";
const std::string db="conn";
const unsigned int port=3306;

int main()
{
    //获取客户端的版本信息
    // cout<<"mysql client version: "<<mysql_get_client_info()<<endl;
    MYSQL* my = mysql_init(nullptr);
    if(nullptr == my)
    {
        std::cerr <<"init mysql error"<<std::endl;
        return 1;
    }
    
    if(mysql_real_connect(my,host.c_str(),user.c_str(),password.c_str(),db.c_str(),port,nullptr,0)==nullptr)
    {
        std::cerr<<"connect MySql error"<<std::endl;
        return 2;
    }

    std::cout<<"connect Mysql success"<<std::endl;
    mysql_set_character_set(my,"utf8");
    //std::string sql="insert into user (name,age,telphone) values ('张三',15,'55566655')";
    std::string sql = "select * from user";
    int n = mysql_query(my,sql.c_str());
    
    if(n==0)
        std::cout<<sql<<"success:"<<n<<std::endl;
    else
        std::cout<<sql<<"failed:"<<n<<std::endl;

    MYSQL_RES* res = mysql_store_result(my);

    int rows = mysql_num_rows(res);
    int fields = mysql_num_fields(res);

    MYSQL_FIELD* fields_array = mysql_fetch_fields(res);
    
    for(int i = 0;i<fields;i++)
    {
        std::cout<<fields_array[i].name<<"\t";
    }
    std::cout<<std::endl;
    for(int i = 0;i<rows;i++)
    {
        MYSQL_ROW row = mysql_fetch_row(res);
        for(int j = 0;j<fields;j++)
        {
            std::cout<<row[j]<<"\t";
        }
        std::cout<<std::endl;
    }
    std::cout<<fields_array[0].db<<"\t"<<fields_array[0].table<<std::endl;

    mysql_free_result(res);
    // while(true)
    // {
    //     std::cout<<"MySql>>>";
    //     if(!std::getline(std::cin,sql) || sql=="quit")
    //     {
    //         std::cout<<"bey bey"<<std::endl;
    //         break;
    //     }
    //     int n = mysql_query(my,sql.c_str());
    //     if(n==0)
    //         std::cout<<sql<<"success:"<<n<<std::endl;
    //     else
    //         std::cout<<sql<<"failed:"<<n<<std::endl;
    // }
    // sleep(10);
    mysql_close(my);

    return 0;
}
